<?php


namespace App\Http\Controllers\Api\V1\Front\User;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Team;
use App\Models\User;
use App\Models\UserContract;
use App\Models\UserInformation;
use App\Models\UserFollow;
use App\Models\Order;
use App\Libs\httpUtil;
use App\Libs\WXBizDataCrypt;
use App\Models\UserPartitionTeam;
use App\Models\UserPartitionTeamLog;
use App\Models\UserRelation;
use App\Services\Front\IndexService;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function ologin(Request $request)
    {
        $number = $request->number;
        if (!$number) {
            return $this->apiResponse("", [
                'errorCode' => '31029',
                'errorMessage' => "账号不存在"
            ]);
        }
        $numberArray = str_split($number);
        $sql = User::select('t1.userId', 't1.membershipId', 't1.level', 't1.userLockStatus', 't1.lockBreak', 't1.lockType', 't1.loginErrorNum', 't1.lockTime')
            ->from((new User())->getTable() . ' as t1')
            ->join((new UserInformation())->getTable() . ' as t2', 't1.userId', '=', 't2.userId');
        if (count($numberArray) == 11) {
            $sql->where('t2.phone', $number);
        } else {
            $sql->where('t1.membershipId', $number);
        }
        $user = $sql->where('logoutStatus', 0)->first();
        if (!$user) {
            return $this->apiResponse("", [
                'errorCode' => '31029',
                'errorMessage' => "账号不存在"
            ]);
        }
        if ($user['userLockStatus']) {
            if ($user['lockType'] == 1) {
                return $this->apiResponse("", [
                    'errorCode' => '32012',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            } else if ($user['lockType'] == 2) {
                return $this->apiResponse("", [
                    'errorCode' => '32013',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            } else {
                return $this->apiResponse("", [
                    'errorCode' => '32014',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            }
        }
        unset($user['userLockStatus']);
        unset($user['lockBreak']);
        unset($user['lockType']);
        return $this->apiResponse($user);
    }

    /**
     * 用户登录
     * @param Request $request [description]
     * @return [type]           [description]
     */
    public function login(Request $request)
    {
        $userId = $request->userId;
        $password = $request->password;

        $sql = User::select('t1.userId', 't1.membershipId', 't1.level', 't3.postId', 't3.postName', 't2.userName', 't2.sex', 't2.birthday', 't2.phone', 't2.email', 't2.personalPhoto',
            't1.inviteUserId', 't1.inviteMembershipId', 't1.isBrilliant', 't1.isFront', 't1.isCentre', 't1.centreJurisdiction', 't1.isManager', 't1.managerJurisdiction', 't1.createTime',
            'userLockStatus', 'logoutStatus', 'password', 't1.loginErrorNum', 't1.lockTime', 't1.lockBreak')
            ->from((new User())->getTable() . ' as t1')
            ->join((new UserInformation())->getTable() . ' as t2', 't1.userId', '=', 't2.userId')
            ->leftJoin((new Post())->getTable() . ' as t3', 't1.postId', '=', 't3.postId')
            ->where('logoutStatus', 0)
            ->where('t1.userId', $userId);
        $user = $sql->first();
        if (!$user) {
            return $this->apiResponse("", [
                'errorCode' => '31029',
                'errorMessage' => "账号不存在"
            ]);
        }
        if ($user['userLockStatus']) {
            if ($user['lockType'] == 1) {
                return $this->apiResponse("", [
                    'errorCode' => '32012',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            } else if ($user['lockType'] == 2) {
                return $this->apiResponse("", [
                    'errorCode' => '32013',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            } else {
                return $this->apiResponse("", [
                    'errorCode' => '32014',
                    'errorMessage' => "于" . $user['lockTime'] . "因为" . $user['lockBreak']
                ]);
            }
        }
        if (md5("liuliuliu" . $password) != $user['password']) {
            if ($user['level'] == 3) {
                $num = 2;
            } else {
                $num = 4;
            }
            if ($user['loginErrorNum'] < $num) {
                User::where('userId', $user['userId'])->increment('loginErrorNum', 1);
                return $this->apiResponse("", [
                    'errorCode' => '30001',
                    'errorMessage' => "密码错误,剩余" . ($num - $user['loginErrorNum']) . "次机会"
                ]);
            } else {
                User::where('userId', $user['userId'])->update(['loginErrorNum' => $num + 1, 'lockTime' => date("Y-m-d H:i:s"), 'lockBreak' => "连续" . ($num + 1) . "次密码输入错误", 'lockType' => 1, 'userLockStatus' => 1]);
                return $this->apiResponse("", [
                    'errorCode' => '32012',
                    'errorMessage' => "于" . date("Y-m-d H:i:s") . "因为连续" . ($num + 1) . "次密码输入错误"
                ]);
            }
        }
        $accessToken = md5(time() . $user['userId']);
        \RedisDB::del($user['userId']);
        \RedisDB::set($user['userId'], $accessToken);
        $user['accessToken'] = $accessToken;
        unset($user['password']);
        User::where('userId', $user['userId'])->update(['accessToken' => $accessToken, 'loginTime' => date("Y-m-d H:i:s"), 'loginNum' => \DB::raw("loginNum + 1"),
            'loginErrorNum' => 0, 'isOnline' => 1, 'onlineTime' => date("Y-m-d H:i:s")]);
        return $this->apiResponse($user);
    }

    public function code(Request $request)
    {
        $phone = $request->phone;
        $code = rand(10000, 99999);
        \RedisDB::setex($phone, 300, $code);
        return $this->apiResponse($code);
    }

    public function register(Request $request)
    {
        $userName = $request->userName;
        $sex = $request->sex;
        $phone = $request->phone;
        $code = $request->code;
        $password = $request->password;
        $inviteMembershipId = $request->membershipId;
        if (!$userName || !$sex || !$phone || !$code || !$password) {
            return $this->apiResponse(null, config('errorLiu.NOTCANSHUID'));
        }
        $smsCode = \RedisDB::get($phone);
        if ($code != $smsCode) {
            return $this->apiResponse("", [
                'errorCode' => '30004',
                'errorMessage' => "验证码错误"
            ]);
        }
        $num = UserInformation::where('phone', $phone)->count();
        if ($num) {
            return $this->apiResponse("", [
                'errorCode' => '30005',
                'errorMessage' => "手机号已被注册"
            ]);
        }
        $inviteUser = null;
        if (isset($inviteMembershipId) && !empty($inviteMembershipId)) {
            $inviteUser = User::select('t1.userId', 't1.membershipId', 't1.level', 't2.userName', 't2.sex', 't2.birthday', 't2.phone', 't2.email', 't2.personalPhoto',
                't1.inviteUserId', 't1.inviteMembershipId', 't1.isBrilliant', 't1.isFront', 't1.isCentre', 't1.centreJurisdiction', 't1.isManager', 't1.managerJurisdiction', 't1.createTime', 'userLockStatus', 'logoutStatus', 'password')
                ->from((new User())->getTable() . ' as t1')
                ->join((new UserInformation())->getTable() . ' as t2', 't1.userId', '=', 't2.userId')
                ->where('t1.membershipId', $inviteMembershipId)
                ->where('t1.level', '!=', 3)
                ->first();
            if (!$inviteUser) {
                return $this->apiResponse("", [
                    'errorCode' => '33004',
                    'errorMessage' => "未查询到该推荐人,请确认会员id是否正确"
                ]);
            }
            User::where('userId', $inviteUser['userId'])->increment('inviteUserNum');
            User::where('userId', $inviteUser['userId'])->update(['loginErrorNum' => 0]);
            $user['level'] = 2;
            $user['registerType'] = "USER";
            $user['inviteUserId'] = $inviteUser['userId'];
            $user['inviteMembershipId'] = $inviteUser['membershipId'];
        }
        $time = date("Y-m-d H:i:s");
        try {
            \DB::beginTransaction();
            //新增
            $membershipId = $this->build_order_no();
            $user['membershipId'] = $membershipId;
            $user['createTime'] = $time;
            $user['brilliantTime'] = $time;
            $user['password'] = md5("liuliuliu" . $password);
            $userInformation['createTime'] = $time;
            $userInformation['userName'] = $userName;
            $userInformation['sex'] = $sex;
            $userInformation['phone'] = $phone;
            $userContract['createTime'] = $time;
            $userId = User::insertGetId($user);
            $userInformation['membershipId'] = $user['membershipId'];
            $userInformation['userId'] = $userId;
            $userContract['userId'] = $userId;
            UserInformation::insert($userInformation);
            UserContract::insert($userContract);
            if (isset($inviteUser)) {
                //确实有人,准备查看是否具有团队
                $inviteUserPartitionTeam = Team::select('*')
                    ->where('userId', $inviteUser['userId'])
                    ->first();
                if ($inviteUserPartitionTeam) {
                    //准备加入团队
                    $user = [];
                    $user['partitionId'] = $inviteUserPartitionTeam['partitionId'];
                    $user['teamId'] = $inviteUserPartitionTeam['teamId'];
                    $user['isAssociation'] = $inviteUserPartitionTeam['isAssociation'];
                    $user['level'] = 2;
                    User::where('userId', $userId)->update($user);
                    $userPartitionTeam = [];
                    $userPartitionTeam['userId'] = $userId;
                    $userPartitionTeam['teamId'] = $inviteUserPartitionTeam['teamId'];
                    $userPartitionTeam['createTime'] = $time;
                    $userPartitionTeam['level'] = 2;
                    UserPartitionTeamLog::insert($userPartitionTeam);
                }
                $userRelation = [];
                $userRelation['userId'] = $userId;
                $userRelation['inviteUserId'] = $inviteUser['userId'];
                $userRelation['relationList'] = ";" . $inviteUser['userId'] . ";";
                $userRelation['createTime'] = $time;
                $inviteUserRelation = UserRelation::where('userId', $inviteUser['userId'])->first();
                if ($inviteUserRelation) {
                    $userRelation['relationList'] = ";" . $inviteUser['userId'] . $inviteUserRelation['relationList'];
                }
                UserRelation::insert($userRelation);
            }
            $sql = User::select('t1.userId', 't1.membershipId', 't1.level', 't3.postId', 't3.postName', 't2.userName', 't2.sex', 't2.birthday', 't2.phone', 't2.email', 't2.personalPhoto',
                't1.inviteUserId', 't1.inviteMembershipId', 't1.isBrilliant', 't1.isFront', 't1.isCentre', 't1.centreJurisdiction', 't1.isManager', 't1.managerJurisdiction', 't1.createTime',
                'userLockStatus', 'logoutStatus', 'password', 't1.loginErrorNum', 't1.lockTime', 't1.lockBreak')
                ->from((new User())->getTable() . ' as t1')
                ->join((new UserInformation())->getTable() . ' as t2', 't1.userId', '=', 't2.userId')
                ->leftJoin((new Post())->getTable() . ' as t3', 't1.postId', '=', 't3.postId')
                ->where('logoutStatus', 0)
                ->where('t1.userId', $userId);
            $user = $sql->first();
            $accessToken = md5(time() . $user['userId']);
            \RedisDB::del($user['userId']);
            \RedisDB::set($user['userId'], $accessToken);
            $user['accessToken'] = $accessToken;
            unset($user['password']);
            User::where('userId', $user['userId'])->update(['accessToken' => $accessToken, 'loginTime' => date("Y-m-d H:i:s"), 'loginNum' => \DB::raw("loginNum + 1"),
                'loginErrorNum' => 0, 'isOnline' => 1, 'onlineTime' => date("Y-m-d H:i:s")]);
            \DB::commit();
            return $this->apiResponse($user);
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::error("CommonController excel error message:" . $e->getMessage());
            return $this->apiResponse('', [
                'errorCode' => "11011",
                'errorMessage' => $e->getMessage()
            ]);
        }
    }
}
